<?php
class Offline_class_model extends CI_Model{

 	function __construct(){
    	parent::__construct();
	}


	public function get_class_plan($user_id)
	{
		$sql = "select plan.id,cla.class_name,cla.class_num,plan.title,plan.class_date,plan.class_time,plan.class_hour,plan.class_type,plan.status,sch.school_name,tea.teacher_name,room.name as class_room_name
		from {$this->db->dbprefix}o2o_class_plan plan
		left join {$this->db->dbprefix}o2o_class cla on cla.id = plan.class_id
		left join {$this->db->dbprefix}o2o_school sch on sch.id=plan.school_id
		left join {$this->db->dbprefix}o2o_teachers tea on tea.id = plan.teacher_id
		left join {$this->db->dbprefix}o2o_classroom room on room.id = plan.class_room
		where plan.class_id in (select cs.class_id from {$this->db->dbprefix}o2o_class_student cs where cs.student_id=(select stu.student_id from {$this->db->dbprefix}o2o_student stu where stu.user_id = {$user_id} limit 1))";
		return $this->db->query($sql)->result_array();
	}

  function get_class_by_code($code,$school_id){
    if($code){
      $sql = "SELECT count(0) as co from {$this->db->dbprefix}o2o_class where school_id = $school_id and class_join_code='{$code}'";
      $class = $this->db->query($sql)->row_array();
      if($class['co'] ==1){
        $sql1 = "SELECT id from {$this->db->dbprefix}o2o_class where school_id = $school_id and class_join_code='{$code}' limit 1";
        $class1 = $this->db->query($sql1)->row_array();
        if($class1){
          return $class1['id'];
        }else{
          return 0;
        }
      }else{
        return 0;
      }

    }else{
      return -1;
    }

  }

  function join_class($user_id,$class_id){

    $user_student_info = get_field_by_where("o2o_student", "student_id", "user_id='{$user_id}'");
    $student_class = get_field_by_where("o2o_class_student", "id", "class_id='{$class_id}' AND student_id = '{$user_student_info['student_id']}'");
    if($student_class){
      return 0;
    }else{
      $class_student_data['class_id'] = $class_id;
      $class_student_data['student_id'] = $user_student_info['student_id'];
      $class_student_data['from'] = 0;
      $class_student_data['add_time'] = time();
      $this->db->insert("o2o_class_student", $class_student_data);
      return 1;
    }

  }
}
